package yz.cp.back.user.service;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import yz.cp.back.auth.security.SecUser;
import yz.cp.back.common.res.ApiResult;
import yz.cp.back.f.entity.FinanceChargeDraw;
import yz.cp.back.f.entity.FinanceDeal;
import yz.cp.back.f.service.IFinanceChargeDrawService;
import yz.cp.back.f.service.IFinanceDealService;
import yz.cp.back.u.entity.UserAccount;
import yz.cp.back.u.entity.UserRole;
import yz.cp.back.u.service.IUserAccountService;
import yz.cp.back.u.service.IUserRoleService;
import yz.cp.back.user.vo.FinanceChargeBo;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.time.ZoneId;

/**
 * @author Administrator
 */
@Service
@Transactional(rollbackFor = Exception.class)
public class FinanceAuditManage {
    @Autowired
    private IFinanceChargeDrawService financeChargeDrawService;
    @Autowired
    private IUserAccountService userAccountService;
    @Autowired
    private IUserRoleService userRoleService;
    @Autowired
    private IFinanceDealService financeDealService;
    @Autowired
    private SerialNumberService serialNumberService;

    /**
     * 充值或提现审核
     */

    public ApiResult audit(FinanceChargeBo bo, SecUser secUser) {

        // 获取充值或提现申请记录
        FinanceChargeDraw financeChargeDraw = financeChargeDrawService.getById(bo.getId());
        if (financeChargeDraw == null) {
            return ApiResult.Custom().failure("记录id有误！");
        }

        if (!financeChargeDraw.getStatus().equals(0)) {
            return ApiResult.Custom().failure("记录已被审核，请勿重复操作！");
        }
        if (StringUtils.isBlank(bo.getRemarks())) {
            return ApiResult.Custom().failure("缺少备注");
        }
        if (financeChargeDraw.getType().equals(1)) {
            if (bo.getStatus() != null && bo.getStatus().equals(1)) {
                if (StringUtils.isBlank(bo.getVoucherNo())) {
                    return ApiResult.Custom().failure("缺少凭证号");
                }
                if (bo.getRamount() == null) {
                    return ApiResult.Custom().failure("缺少确认金额");
                }
                if (bo.getRamount().compareTo(financeChargeDraw.getAmount())>0) {
                    return ApiResult.Custom().failure("确认金额不一致");
                }
            }

        } else {
            if (bo.getStatus() != null && bo.getStatus().equals(1)) {
                if (StringUtils.isBlank(bo.getVoucherNo())) {
                    return ApiResult.Custom().failure("缺少凭证号");
                }
                if (StringUtils.isBlank(bo.getVoucher())) {
                    return ApiResult.Custom().failure("缺少上传凭证");
                }
            }
        }
        if (bo.getStatus() != null && bo.getStatus().equals(1)) {
            if (financeChargeDrawService.count(new QueryWrapper<FinanceChargeDraw>().lambda()
                    .eq(FinanceChargeDraw::getVoucherNo, bo.getVoucherNo())) > 0) {
                return ApiResult.Custom().failure("凭证号重复");
            }
        }

        financeChargeDraw.setUby(secUser.getId());
        financeChargeDraw.setRby(secUser.getUsername());
        financeChargeDraw.setRamount(bo.getRamount());
        financeChargeDraw.setRtime(Long.valueOf(LocalDateTime.now().atZone(ZoneId.systemDefault()).toInstant().getEpochSecond()).intValue());
        // 获取用户角色信息
        UserRole userRole = userRoleService.getById(financeChargeDraw.getMerchantId());
        if (userRole == null) {
            return ApiResult.Custom().failure("商户记录未找到！");
        }

        //获取用户账户
        UserAccount userAccount = userAccountService.getById(financeChargeDraw.getMerchantId());
        BigDecimal amount = financeChargeDraw.getAmount();
        // 保存交易记录
        FinanceDeal financeDeal = new FinanceDeal();
        financeDeal.setRemarks(financeChargeDraw.getRemarks());
        financeDeal.setMsctime(System.currentTimeMillis() / 1000);
        financeDeal.setNo(serialNumberService.generate());
        financeDeal.setAccountId(financeChargeDraw.getMerchantId());
        financeChargeDraw.setStatusRemarks(bo.getRemarks());
        if (bo.getStatus() == 1) {
            //审核通过
            financeChargeDraw.setStatus(1);
            financeChargeDraw.setVoucherNo(bo.getVoucherNo());
            financeDeal.setAmount(bo.getRamount());
            financeDeal.setStatus(true);
            if (financeChargeDraw.getType() == 1) {
                financeDeal.setAccountId(financeChargeDraw.getMerchantId());
                //充值
                if (financeChargeDraw.getEaccountType() == 1) {
                    //资金账户充值
                    financeDeal.setType(11);

                    userAccount.setMoneyAmount(userAccount.getMoneyAmount().add(amount));
                    userAccount.setMoneyUsable(userAccount.getMoneyUsable().add(amount));
                    userAccount.setMoneyTotalTopup(userAccount.getMoneyTotalTopup().add(amount));


                } else if (financeChargeDraw.getEaccountType() == 2) {
                    //保证金账户充值
                    financeDeal.setType(111);
                    userAccount.setDepositAmount(userAccount.getDepositAmount().add(amount));
                    userAccount.setDepositUsable(userAccount.getDepositUsable().add(amount));
                    userAccount.setDepositTotalTopup(userAccount.getDepositTotalTopup().add(amount));
                }
            } else if (financeChargeDraw.getType() == 2) {

                //提现
                if (financeChargeDraw.getEaccountType() == 1) {
                    //资金账户提现
                    financeDeal.setType(21);
                    userAccount.setMoneyAmount(userAccount.getMoneyAmount().subtract(amount));
                    userAccount.setMoneyInTransit(userAccount.getMoneyInTransit().subtract(amount));
                    userAccount.setMoneyTotalWithdraw(userAccount.getMoneyTotalWithdraw().add(amount));

                } else if (financeChargeDraw.getEaccountType() == 2) {
                    //保证金账户提现
                    financeDeal.setType(211);
                    userAccount.setDepositAmount(userAccount.getDepositAmount().subtract(amount));
                    userAccount.setDepositInTransit(userAccount.getDepositInTransit().subtract(amount));
                    userAccount.setDepositTotalWithdraw(userAccount.getDepositTotalWithdraw().add(amount));

                }
            }
            financeDealService.save(financeDeal);
            //保存账户信息
            userAccountService.saveOrUpdate(userAccount);
        } else {
            //审核拒绝
            financeChargeDraw.setStatus(2);
            //归还冻结金额 针对提现
            if (financeChargeDraw.getType() == 2) {
                financeDeal.setAmount(amount);
                financeDeal.setStatus(false);
                financeDeal.setAccountId(financeChargeDraw.getMerchantId());
                if (financeChargeDraw.getType() == 1) {
                    //提现
                    if (financeChargeDraw.getEaccountType() == 1) {
                        //资金账户提现
                        financeDeal.setType(11);
                        userAccount.setMoneyUsable(userAccount.getMoneyUsable().add(amount));
                        userAccount.setMoneyInTransit(userAccount.getMoneyInTransit().subtract(amount));


                    } else if (financeChargeDraw.getEaccountType() == 2) {
                        //保证金账户提现
                        financeDeal.setType(111);
                        userAccount.setDepositUsable(userAccount.getDepositUsable().add(amount));
                        userAccount.setDepositInTransit(userAccount.getDepositInTransit().subtract(amount));

                    }

                } else {
                    if (financeChargeDraw.getEaccountType() == 1) {
                        financeDeal.setType(21);
                    } else {
                        financeDeal.setType(211);
                    }

                }
                financeDealService.save(financeDeal);
                //保存账户信息
                userAccountService.saveOrUpdate(userAccount);
            }
        }
        //保存交易流水

        //更新申请记录
        financeChargeDrawService.saveOrUpdate(financeChargeDraw);

        return ApiResult.Custom().success("审核完成！");

    }
}
